package com.azlogica.control;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import com.azlogica.entity.Frame;

public class GpsService extends Service implements LocationListener {
	private LocationManager locationManager;
	private String provider;
	int level;
	ManageFrame mf;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mf = new ManageFrame(this);
		Toast.makeText(this, "Iniciado ", Toast.LENGTH_SHORT).show();
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			System.out.println("Provider " + provider + " has been selected.");
			onLocationChanged(location);
		}
		locationManager.requestLocationUpdates(provider, 30000, 10, this);
		return Service.START_STICKY;
	}

	@Override
	public void onLocationChanged(Location location) {
		Frame f = new Frame(location, this);
		String frame = mf.buildFrame(f);
		createFrameOnDatabase(f);
		sendData(frame);
		//Toast.makeText(this, f.getFrame(), Toast.LENGTH_SHORT).show();
		//sendData(f.getFrame());
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	public void createFrameOnDatabase(Frame f){
		mf.CreateFrame(f.getHeader(), f.getReport(), f.getSack(), f.getMessType(), 
				f.getImei(), f.getStatus(), f.getNumber(), f.getAccuracy(), f.getSpeed(), f.getAzimuth(), 
				f.getAltitude(), f.getLongitude(), f.getLatitude(), f.getGpsUTC(), f.getMcc(), 
				f.getMnc(), f.getLac(), f.getCllId(), f.getBattery(), f.getSendTime());
	}
	
	public void sendData(String frame) {
		Connection con = new Connection("10.0.2.2", 11000, frame);
		con.execute();
	}
}